<?php

namespace M\Action;

use Common\Action\FirstendAction;

class BaseAction extends FirstendAction
{
    public function _initialize()
    {
        parent::_initialize();
        $tkapi = F('tqkapi/api');
        $this->tqkuid = C('yh_app_kehuduan');
        $this->assign('trackurl', $this->trackid());
        $this->accessKey = trim(C('yh_gongju'));
        if (false === $tkapi) {
            $this->tqkapi = 'http://api.tuiquanke.com';
        } else {
            $this->tqkapi = $tkapi;
        }

    }


    protected function fullurl()
    {
        $mdomain = str_replace('/index.php/m', '', C('yh_headerm_html'));
        $url = urlencode($mdomain . $_SERVER["REQUEST_URI"]);
        return $url;
    }


    protected function nav()
    {
        $where = array(
            'status' => 1,
            'type' => 'main'
        );

        $navlist = M('nav')->cache(true, 50 * 60)->field('name,alias,link,target')->where($where)->order('ordid asc')->select();
        return $navlist;
    }


    protected function weixinlogin()
    {

        if (C('yh_site_tiaozhuan') == 1) {
            $useragent = strtolower(addslashes($_SERVER['HTTP_USER_AGENT']));
            if (IS_POST && strpos($useragent, 'micromessenger') > 0) {
                $param = I('post.');

                if ($param['wx_openkey'] == $this->accessKey && $param['wx_status'] == 'ok') {
                    $res = $this->_wechat_login($param);
                    if (!$res) {

//                        if (C('yh_index_ems') == 1 || (strpos($_SERVER['QUERY_STRING'], '/user/canvas-mask.html') > 0)) {

                        $mod = M('user');
                        $track_val = cookie('trackid');
                        if (!empty($track_val)) {
                            $track = unserialize($track_val);
                            $uid = $track['t'];
                            if ($uid > 0) {
                                $where = array(
                                    'id' => $uid
                                );
                                $exist = $mod->field('id,username,nickname,phone,email,fuid,guid,invocode,avatar,password,score,tbname,money,webmaster,webmaster_rate,oid')->where($where)->find();
                            }

                        }
                        $now = NOW_TIME;
                        $phone = $now;
                        $pwd = md5($param['wx_openid']);
                        $openid = $param['wx_openid'];
                        $nickname = $param['wx_nickname'];

                        $info = array(
                            'username' => $nickname,
                            'phone' => $phone,
                            'nickname' => $nickname,
                            'password' => $pwd,
                            'reg_ip' => get_client_ip(),
                            'avatar' => $param['wx_headimgurl'],
                            'state' => 1,
                            'status' => 1,
                            'reg_time' => $now,
                            'last_time' => $now,
                            'create_time' => $now,
                            'openid' => $openid,
                            'fuid' => isset($exist['fuid']) ? $exist['fuid'] : 0,
                            'guid' => isset($exist['guid']) ? $exist['guid'] : 0,
                            'tbname' => 1   // enable 产品推广
                        );
                        $res = $mod->add($info);
                        $this->visitor->wechatlogin($openid);

//                        } else {
//                            echo '<form  id="form1" style="display:none" name="form1" method="post" action="' . U('login/fillphone') . '">
//			  <input name="wx_openid" type="text" value="' . $param['wx_openid'] . '"/>
//			  <input name="wx_nickname" type="text" value="' . $param['wx_nickname'] . '"/>
//			  <input name="wx_headimgurl" type="text" value="' . $param['wx_headimgurl'] . '"/>
//			   <input name="wx_callback" type="text" value="' . $param['wx_callback'] . '"/>
//			</form>
//			<script type="text/javascript">function load_submit(){document.form1.submit()}load_submit();</script>';
//                        }

                    }
                    cookie("iswechat", 'error3', 1200);
                    echo('<script>window.location.href="' . $param['wx_callback'] . '"</script>');
                }

            }

//	cookie("iswechat")!="error3" && 
            if (strpos($useragent, 'micromessenger') > 0 && $this->visitor->is_login == false) {
                $apiurl = 'http://app.tuiquanke.cn/wechatlogin?uid=' . $this->tqkuid . '&time=' . NOW_TIME . '&callback=' . $this->fullurl();
                echo('<script>window.location.href="' . $apiurl . '"</script>');
                exit;
            }

        }


    }


    protected function buyer($num = '1')
    {

        $cach_name = "buyercache";
        $arraytime = array('35', '40', '50', '33', '36', '42', '48', '27', '6', '13', '1', '12', '3', '14', '5', '16', '7', '18', '9', '10', '15', '20', '22', '30', '35', '40', '50', '33', '36', '42', '48', '27', '6', '13');
        $datainfo = S($cach_name);
        if (false === $datainfo || empty($datainfo)) {
            $userlist = M('user')->field('nickname,avatar')->where('state=0')->order('rand()')->limit(1000)->select();
            S($cach_name, $userlist, 86400);
            $datainfo = $userlist;
        }
        $result = array_rand($datainfo, $num);
        $timelist = array_rand($arraytime, $num);
        foreach ($result as $k => $v) {
            $data[$k]['nickname'] = $this->shortname($datainfo[$v]['nickname']);
            $data[$k]['avatar'] = $datainfo[$v]['avatar'];
            $data[$k]['time'] = $timelist[$k];
        }

        return $data;

    }


    protected function trackid()
    {
        $track = I('t', '0', 'number_int');
        $isagent = cookie('createagent');
        if ((!empty($track) && $track != $isagent && is_numeric($track)) || (false === $isagent && !empty($track) && is_numeric($track))) {
            $res = M('user')->field('webmaster_pid,pdd_pid')->where(array('id' => $track))->find();
            if ($res) {
                $data = array(
                    't_pid' => $res['webmaster_pid'],
                    'p_pid' => $res['pdd_pid'],
                    't' => $track,
                );
                $data = serialize($data);
            }
            cookie("trackid", $data, 86400 * 15);
            cookie('createagent', $track);
        }
        $trackid = cookie('trackid');
        if (!empty($trackid)) {
            $data = unserialize($trackid);
            $trackurl = '?t=' . $data['t'];
            return $trackurl;
        }

        if ($this->visitor->is_login) {
            $webmaster = $this->visitor->get();
            if ($webmaster['webmaster'] == 1) {
                $data = array(
                    't_pid' => $webmaster['webmaster_pid'],
                    'p_pid' => $webmaster['pdd_pid'],
                    't' => $webmaster['id'],
                );
                $data = serialize($data);
                cookie("trackid", $data, 86400 * 15);
                $trackurl = '?t=' . $webmaster['id'];
                return $trackurl;
            }
        }

    }


    protected function shortname($txt)
    {
        $username = mb_substr($txt, 0, 1, 'utf-8') . '***' . mb_substr($txt, -1, 1, 'utf-8');
        return $username;
    }


}